﻿<!-- <script lang="ts" setup name="productionOrder">
import { ref, reactive, onMounted } from "vue";
import { auth } from '/@/utils/authFunction';
import { ElMessageBox, ElMessage } from "element-plus";
import { downloadStreamFile } from "/@/utils/download";
import { useProductionOrderApi } from '/@/api/baseproductionorder/productionOrder';
import editDialog from '/@/views/baseproductionorder/productionOrder/component/editDialog.vue'
import printDialog from '/@/views/system/print/component/hiprint/preview.vue'
import ModifyRecord from '/@/components/table/modifyRecord.vue';
import ImportData from "/@/components/table/importData.vue";

const productionOrderApi = useProductionOrderApi();
const printDialogRef = ref();
const editDialogRef = ref();
const importDataRef = ref();
const state = reactive({
  exportLoading: false,
  tableLoading: false,
  stores: {},
  showAdvanceQueryUI: false,
  dropdownData: {} as any,
  selectData: [] as any[],
  tableQueryParams: {} as any,
  tableParams: {
    page: 1,
    pageSize: 20,
    total: 0,
    field: 'createTime', // 默认的排序字段
    order: 'descending', // 排序方向
    descStr: 'descending', // 降序排序的关键字符
  },
  tableData: [],
});

// 页面加载时
onMounted(async () => {
});

// 查询操作
const handleQuery = async (params: any = {}) => {
  state.tableLoading = true;
  state.tableParams = Object.assign(state.tableParams, params);
  const result = await productionOrderApi.page(Object.assign(state.tableQueryParams, state.tableParams)).then(res => res.data.result);
  state.tableParams.total = result?.total;
  state.tableData = result?.items ?? [];
  state.tableLoading = false;
};

// 列排序
const sortChange = async (column: any) => {
  state.tableParams.field = column.prop;
  state.tableParams.order = column.order;
  await handleQuery();
};

// 删除
const delProductionOrder = (row: any) => {
  ElMessageBox.confirm(`确定要删除吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await productionOrderApi.delete({ id: row.id });
    handleQuery();
    ElMessage.success("删除成功");
  }).catch(() => {});
};

// 批量删除
const batchDelProductionOrder = () => {
  ElMessageBox.confirm(`确定要删除${state.selectData.length}条记录吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await productionOrderApi.batchDelete(state.selectData.map(u => ({ id: u.id }) )).then(res => {
      ElMessage.success(`成功批量删除${res.data.result}条记录`);
      handleQuery();
    });
  }).catch(() => {});
};


handleQuery();
</script>
<template>
  <div class="productionOrder-container" v-loading="state.exportLoading">
    <el-card shadow="hover" :body-style="{ paddingBottom: '0' }"> 
      <el-form :model="state.tableQueryParams" ref="queryForm" labelWidth="90">
        <el-row>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item label="关键字">
              <el-input v-model="state.tableQueryParams.keyword" clearable placeholder="请输入模糊查询关键字"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="工单类型">
              <el-input v-model="state.tableQueryParams.productionOrderType" clearable placeholder="请输入工单类型"/>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="物料编码">
              <el-input v-model="state.tableQueryParams.productCode" clearable placeholder="请输入物料编码"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="物料名称">
              <el-input v-model="state.tableQueryParams.productName" clearable placeholder="请输入物料名称"/>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="单位编码">
              <el-input v-model="state.tableQueryParams.unitCode" clearable placeholder="请输入单位编码"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="单位名称">
              <el-input v-model="state.tableQueryParams.unitName" clearable placeholder="请输入单位名称"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="计划数量">
              <el-input-number v-model="state.tableQueryParams.quantity"  clearable placeholder="请输入计划数量"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="完成数量">
              <el-input-number v-model="state.tableQueryParams.finishQuantity"  clearable placeholder="请输入完成数量"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item >
              <el-button-group style="display: flex; align-items: center;">
                <el-button type="primary"  icon="ele-Search" @click="handleQuery" v-auth="'productionOrder:page'" v-reclick="1000"> 查询 </el-button>
                <el-button icon="ele-Refresh" @click="() => state.tableQueryParams = {}"> 重置 </el-button>
                <el-button icon="ele-ZoomIn" @click="() => state.showAdvanceQueryUI = true" v-if="!state.showAdvanceQueryUI" style="margin-left:5px;"> 高级查询 </el-button>
                <el-button icon="ele-ZoomOut" @click="() => state.showAdvanceQueryUI = false" v-if="state.showAdvanceQueryUI" style="margin-left:5px;"> 隐藏 </el-button>
                <el-button type="primary" style="margin-left:5px;" icon="ele-Plus" @click="editDialogRef.openDialog(null, '新增生产工单')" v-auth="'productionOrder:add'"> 新增 </el-button>

              </el-button-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="full-table" shadow="hover" style="margin-top: 5px">
      <el-table :data="state.tableData" @selection-change="(val: any[]) => { state.selectData = val; }" style="width: 100%" v-loading="state.tableLoading" tooltip-effect="light" row-key="id" @sort-change="sortChange" border>
        <el-table-column type="selection" width="40" align="center" v-if="auth('productionOrder:batchDelete') || auth('productionOrder:export')" />
        <el-table-column type="index" label="序号" width="55" align="center"/>
        <el-table-column prop='productionOrderType' label='工单类型' show-overflow-tooltip />
        <el-table-column prop='productCode' label='物料编码' show-overflow-tooltip />
        <el-table-column prop='productName' label='物料名称' show-overflow-tooltip />
        <el-table-column prop='unitCode' label='单位编码' show-overflow-tooltip />
        <el-table-column prop='unitName' label='单位名称' show-overflow-tooltip />
        <el-table-column prop='quantity' label='计划数量' show-overflow-tooltip />
        <el-table-column prop='finishQuantity' label='完成数量' show-overflow-tooltip />
        <el-table-column label="修改记录" width="100" align="center" show-overflow-tooltip>
          <template #default="scope">
            <ModifyRecord :data="scope.row" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" align="center" fixed="right" show-overflow-tooltip v-if="auth('productionOrder:update') || auth('productionOrder:delete')">
          <template #default="scope">
            <el-button icon="ele-Edit" size="small" text type="primary" @click="editDialogRef.openDialog(scope.row, '编辑生产工单')" v-auth="'productionOrder:update'"> 编辑 </el-button>
            <el-button icon="ele-Delete" size="small" text type="primary" @click="delProductionOrder(scope.row)" v-auth="'productionOrder:delete'"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination 
              v-model:currentPage="state.tableParams.page"
              v-model:page-size="state.tableParams.pageSize"
              @size-change="(val: any) => handleQuery({ pageSize: val })"
              @current-change="(val: any) => handleQuery({ page: val })"
              layout="total, sizes, prev, pager, next, jumper"
              :page-sizes="[10, 20, 50, 100, 200, 500]"
              :total="state.tableParams.total"
              size="small"
              background />
      <ImportData ref="importDataRef" :import="productionOrderApi.importData" :download="productionOrderApi.downloadTemplate" v-auth="'productionOrder:import'" @refresh="handleQuery"/>
      <printDialog ref="printDialogRef" :title="'打印生产工单'" @reloadTable="handleQuery" />
      <editDialog ref="editDialogRef" @reloadTable="handleQuery" />
    </el-card>
  </div>
</template>
<style scoped>
:deep(.el-input), :deep(.el-select), :deep(.el-input-number) {
  width: 100%;
}
</style> -->



<script lang="ts" setup name="productionOrderWithItems">
import { ref, reactive, onMounted } from "vue";
import { auth } from '/@/utils/authFunction';
import { ElMessageBox, ElMessage } from "element-plus";
import { downloadStreamFile } from "/@/utils/download";
import { useProductionOrderApi } from '/@/api/baseproductionorder/productionOrder';
import { useProductionOrderItemsApi } from '/@/api/baseproductionorder/productionOrderItems';
import editDialog from '/@/views/baseproductionorder/productionOrder/component/editDialog.vue'
import editItemsDialog from '/@/views/baseproductionorder/productionOrderItems/component/editDialog.vue'
import printDialog from '/@/views/system/print/component/hiprint/preview.vue'
import ModifyRecord from '/@/components/table/modifyRecord.vue';
import ImportData from "/@/components/table/importData.vue";

const productionOrderApi = useProductionOrderApi();
const productionOrderItemsApi = useProductionOrderItemsApi();
const printDialogRef = ref();
const editDialogRef = ref();
const editItemsDialogRef = ref();
const importDataRef = ref();

const state = reactive({
  exportLoading: false,
  tableLoading: false,
  itemsTableLoading: false,
  showAdvanceQueryUI: false,
  selectData: [] as any[],
  selectItemsData: [] as any[],
  tableQueryParams: {} as any,
  itemsTableQueryParams: {} as any,
  tableParams: {
    page: 1,
    pageSize: 20,
    total: 0,
    field: 'createTime',
    order: 'descending',
    descStr: 'descending',
  },
  itemsTableParams: {
    page: 1,
    pageSize: 20,
    total: 0,
    field: 'createTime',
    order: 'descending',
    descStr: 'descending',
  },
  tableData: [],
  itemsTableData: [],
  currentOrderId: null as string | null, // 当前选中的工单ID
});

// 查询工单列表
const handleQuery = async (params: any = {}) => {
  state.tableLoading = true;
  state.tableParams = Object.assign(state.tableParams, params);
  const result = await productionOrderApi.page(Object.assign(state.tableQueryParams, state.tableParams)).then(res => res.data.result);
  state.tableParams.total = result?.total;
  state.tableData = result?.items ?? [];
  state.tableLoading = false;
  
};

// 查询工单详情
const handleItemsQuery = async (orderId: string) => {
  if (!orderId) return;
  
  state.itemsTableLoading = true;
  state.currentOrderId = orderId;
  state.itemsTableQueryParams.productionOrderId = orderId;
  
  const result = await productionOrderItemsApi.page(
    Object.assign(state.itemsTableQueryParams, state.itemsTableParams)
  ).then(res => res.data.result);
  
  state.itemsTableParams.total = result?.total;
  state.itemsTableData = result?.items ?? [];
  state.itemsTableLoading = false;
};

// 工单选择变化
const handleOrderSelect = (row: any) => {
  handleItemsQuery(row.id);
};

// 删除工单
const delProductionOrder = (row: any) => {
  ElMessageBox.confirm(`确定要删除该工单及其所有详情吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await productionOrderApi.delete({ id: row.id });

    handleQuery();
    ElMessage.success("删除成功");
  }).catch(() => {});
};

// 删除工单详情
const delProductionOrderItem = (row: any) => {
  ElMessageBox.confirm(`确定要删除该工单详情吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await productionOrderItemsApi.delete({ id: row.id });
    if (state.currentOrderId) {
      handleItemsQuery(state.currentOrderId);
    }
    ElMessage.success("删除成功");
  }).catch(() => {});
};

// 列排序
const sortChange = async (column: any, isItems: boolean = false) => {
  if (isItems) {
    state.itemsTableParams.field = column.prop;
    state.itemsTableParams.order = column.order;
    if (state.currentOrderId) {
      await handleItemsQuery(state.currentOrderId);
    }
  } else {
    state.tableParams.field = column.prop;
    state.tableParams.order = column.order;
    await handleQuery();
  }
};

// 批量删除
const batchDel = () => {
  ElMessageBox.confirm(`确定要删除${state.selectData.length}条记录吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await productionOrderApi.batchDelete(state.selectData.map(u => ({ id: u.id }) )).then(res => {
      ElMessage.success(`成功批量删除${res.data.result}条记录`);
      handleQuery();
    });
  }).catch(() => {});
};

// 批量保存
const batchSave = () => {
  if(state.selectData.length != 0){
    // 直接执行审核操作
    productionOrderApi.batchSave(state.selectData.map(u => ({ id: u.id }))).then(res => {
      ElMessage.success(`保存成功`);

      handleQuery();
    })
  }else{
    ElMessage.error(`请至少选中一条记录`);
  }
  
};

// 批量审核
const batchAudit = () => {
  if(state.selectData.length != 0){
    // 直接执行审核操作
    productionOrderApi.batchAudit(state.selectData.map(u => ({ id: u.id }))).then(res => {
      // ElMessage.success(`成功审核${res.data.result}条记录`);
      ElMessage.success(`审核成功`);

      handleQuery();
    })
  }else{
    ElMessage.error(`请至少选中一条记录`);
  }
  
};

// 批量开工
const batchStart = () => {
  if(state.selectData.length != 0){
    // 直接执行审核操作
    productionOrderApi.batchStart(state.selectData.map(u => ({ id: u.id }))).then(res => {
      ElMessage.success(`开工成功`);

      handleQuery();
    })
  }else{
    ElMessage.error(`请至少选中一条记录`);
  }
  
};

// 批量完工
const batchFinish = () => {
  if(state.selectData.length != 0){
    // 直接执行审核操作
    productionOrderApi.batchFinish(state.selectData.map(u => ({ id: u.id }))).then(res => {
      ElMessage.success(`完工成功`);

      handleQuery();
    })
  }else{
    ElMessage.error(`请至少选中一条记录`);
  }
  
};

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="productionOrder-container" v-loading="state.exportLoading">
    <el-card shadow="hover" :body-style="{ paddingBottom: '0' }"> 
      <el-form :model="state.tableQueryParams" ref="queryForm" labelWidth="90">
        <el-row>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item label="关键字">
              <el-input v-model="state.tableQueryParams.keyword" clearable placeholder="请输入模糊查询关键字"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item>
              <el-button-group style="display: flex; align-items: center;">
                <el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'productionOrder:page'">查询</el-button>
                <el-button icon="ele-Refresh" @click="() => { state.tableQueryParams = {}; handleQuery(); }">重置</el-button>
                <el-button type="primary" icon="ele-Plus" @click="editDialogRef.openDialog(null, '新增生产工单')" v-auth="'productionOrder:add'">新增</el-button>
                <!-- <el-button type="danger" style="margin-left:5px;" icon="ele-Delete" @click="batchDel" :disabled="state.selectData.length == 0"> 删除 </el-button> -->
                <el-button type="danger" style="margin-left:5px;" icon="ele-Check" @click="batchSave"> 保存 </el-button>
                <el-button type="danger" style="margin-left:5px;" icon="ele-CircleCheck" @click="batchAudit"> 审核 </el-button>
                <el-button type="danger" style="margin-left:5px;" icon="ele-CircleCheck" @click="batchStart"> 开工 </el-button>
                <el-button type="danger" style="margin-left:5px;" icon="ele-CircleCheckFilled" @click="batchFinish"> 完工 </el-button>

              </el-button-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card  class="full-table" shadow="hover" style="margin-top: 5px">
      <el-table 
        :data="state.tableData" 
        @row-click="handleOrderSelect"
        highlight-current-row
        style="width: 100%" 
        v-loading="state.tableLoading" 
        tooltip-effect="light" 
        row-key="id" 
        @sort-change="sortChange" 
        @selection-change="(val: any[]) => { state.selectData = val; }"
        border
      >
        <el-table-column type="selection" width="40" align="center" v-if="auth('productionOrder:batchDelete') || auth('productionOrder:export')" />
        <el-table-column type="index" label="序号" width="55" align="center"/>
        <el-table-column prop='productionOrderNum' label='工单号' show-overflow-tooltip />
        <el-table-column prop='productCode' label='成品编码' show-overflow-tooltip />
        <el-table-column prop='productName' label='成品名称' show-overflow-tooltip />
        <el-table-column prop='quantity' label='计划数量' show-overflow-tooltip />
        <el-table-column prop='finishQuantity' label='完成数量' show-overflow-tooltip />
        <el-table-column prop='status' label='状态' show-overflow-tooltip />
        <el-table-column prop='processStatus' label='进度状态' show-overflow-tooltip />
        <el-table-column prop='remark' label='备注' show-overflow-tooltip />
        <el-table-column label="操作" width="240" align="center" fixed="right" show-overflow-tooltip>
          <template #default="scope">
            <el-button icon="ele-Edit" size="small" text type="primary" @click="editDialogRef.openDialog(scope.row, '编辑生产工单')" v-auth="'productionOrder:update'">编辑</el-button>
            <!-- <el-button icon="ele-Pointer" size="small" text type="primary" @click="editItemsDialogRef.openDialog({ productionOrderId: state.currentOrderId }, '新增工单详情')"  v-auth="'productionOrderItems:add'">添加详情</el-button> -->
            <el-button icon="ele-Pointer" size="small" text type="primary" @click="editItemsDialogRef.openDialog({ productionOrderId: scope.row.id }, '新增工单详情')"  v-auth="'productionOrderItems:add'">添加详情</el-button>

            <el-button icon="ele-Delete" size="small" text type="primary" @click="delProductionOrder(scope.row)" v-auth="'productionOrder:delete'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination 
        v-model:currentPage="state.tableParams.page"
        v-model:page-size="state.tableParams.pageSize"
        @size-change="(val: any) => handleQuery({ pageSize: val })"
        @current-change="(val: any) => handleQuery({ page: val })"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100, 200, 500]"
        :total="state.tableParams.total"
        size="small"
        background
      />
    </el-card>

    <!-- v-if="state.currentOrderId" -->
     <!-- class="full-table" shadow="hover" style="margin-top: 5px" -->
    <el-card class="full-table" shadow="hover" style="margin-top: 5px">
      <div class="detail-header">
        <h5>工单详情</h5>
      </div>
      <el-table 
        :data="state.itemsTableData" 
        style="width: 100%" 
        v-loading="state.itemsTableLoading" 
        tooltip-effect="light" 
        row-key="id" 
        @sort-change="(column: any) => sortChange(column, true)" 
        border
      >
        <el-table-column type="index" label="序号" width="55" align="center"/>
        <el-table-column prop='productCode' label='明细物料编码' show-overflow-tooltip />
        <el-table-column prop='productName' label='明细物料名称' show-overflow-tooltip />
        <el-table-column prop='quantity' label='计划数量' show-overflow-tooltip />
        <el-table-column prop='finishQuantity' label='完成数量' show-overflow-tooltip />
        <el-table-column prop='remark' label='备注' show-overflow-tooltip />
        <el-table-column label="操作" width="140" align="center" fixed="right" show-overflow-tooltip>
          <template #default="scope">
            <el-button icon="ele-Edit" size="small" text type="primary" @click="editItemsDialogRef.openDialog(scope.row, '编辑工单详情')" v-auth="'productionOrderItems:update'">编辑</el-button>
            <el-button icon="ele-Delete" size="small" text type="primary" @click="delProductionOrderItem(scope.row)" v-auth="'productionOrderItems:delete'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination 
        v-model:currentPage="state.itemsTableParams.page"
        v-model:page-size="state.itemsTableParams.pageSize"
        @size-change="(val: any) => { state.itemsTableParams.pageSize = val; handleItemsQuery(state.currentOrderId!); }"
        @current-change="(val: any) => { state.itemsTableParams.page = val; handleItemsQuery(state.currentOrderId!); }"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100, 200, 500]"
        :total="state.itemsTableParams.total"
        size="small"
        background
      />
    </el-card>
   
    <editDialog ref="editDialogRef" @reloadTable="handleQuery" />
    <editItemsDialog ref="editItemsDialogRef" @reloadTable="() => handleItemsQuery(state.currentOrderId!)" />
    <printDialog ref="printDialogRef" :title="'打印生产工单'" />
  </div>
</template>

<style scoped>
.productionOrder-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

:deep(.el-input), :deep(.el-select), :deep(.el-input-number) {
  width: 100%;
}
</style>

